package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.xuanzheng.company.entity.AttendanceSetting;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.AttendanceSettingService;
import com.xuanzheng.company.service.impl.AttendanceSettingServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/api/attendance/setting")
public class AttendanceSettingServlet extends HttpServlet {
    private AttendanceSettingService attendanceSettingService = new AttendanceSettingServiceImpl();
    private Gson gson = new Gson();
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应类型
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        
        // 获取当前登录用户
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            // 用户未登录
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "用户未登录");
            out.print(gson.toJson(result));
            return;
        }
        
        if (user.getRole() != 1) {
            // 不是公司负责人
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "只有公司负责人可以查看打卡设置");
            out.print(gson.toJson(result));
            return;
        }
        
        // 获取公司ID
        String companyId = req.getParameter("companyId");
        if (companyId == null || companyId.isEmpty()) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "公司ID不能为空");
            out.print(gson.toJson(result));
            return;
        }
        
        // 获取打卡设置
        AttendanceSetting setting = attendanceSettingService.getByCompanyId(companyId);
        
        Map<String, Object> result = new HashMap<>();
        if (setting != null) {
            // 创建一个新的Map来存储格式化后的数据
            Map<String, Object> formattedSetting = new HashMap<>();
            formattedSetting.put("id", setting.getId());
            formattedSetting.put("companyId", setting.getCompanyId());
            formattedSetting.put("companyName", setting.getCompanyName());
            
            // 格式化时间为字符串
            SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
            formattedSetting.put("checkInStartTime", timeFormat.format(setting.getCheckInStartTime()));
            formattedSetting.put("checkInEndTime", timeFormat.format(setting.getCheckInEndTime()));
            formattedSetting.put("checkOutStartTime", timeFormat.format(setting.getCheckOutStartTime()));
            formattedSetting.put("checkOutEndTime", timeFormat.format(setting.getCheckOutEndTime()));
            
            // 添加绩点相关字段
            formattedSetting.put("maxAttendanceHours", setting.getMaxAttendanceHours());
            formattedSetting.put("attendancePercentage", setting.getAttendancePercentage());
            formattedSetting.put("taskPercentage", setting.getTaskPercentage());
            
            // 格式化创建时间和更新时间
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (setting.getCreateTime() != null) {
                formattedSetting.put("createTime", dateFormat.format(setting.getCreateTime()));
            }
            if (setting.getUpdateTime() != null) {
                formattedSetting.put("updateTime", dateFormat.format(setting.getUpdateTime()));
            }
            
            result.put("success", true);
            result.put("data", formattedSetting);
        } else {
            result.put("success", false);
            result.put("message", "未找到打卡设置");
        }
        
        out.print(gson.toJson(result));
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应类型
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        
        // 获取当前登录用户
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            // 用户未登录
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "用户未登录");
            out.print(gson.toJson(result));
            return;
        }
        
        if (user.getRole() != 1) {
            // 不是公司负责人
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "只有公司负责人可以设置打卡时间");
            out.print(gson.toJson(result));
            return;
        }
        
        // 读取请求体中的JSON数据
        BufferedReader reader = req.getReader();
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        
        try {
            // 解析JSON数据
            JsonObject jsonObject = gson.fromJson(sb.toString(), JsonObject.class);
            
            String companyId = jsonObject.get("companyId").getAsString();
            String checkInStartTime = jsonObject.get("checkInStartTime").getAsString();
            String checkInEndTime = jsonObject.get("checkInEndTime").getAsString();
            String checkOutStartTime = jsonObject.get("checkOutStartTime").getAsString();
            String checkOutEndTime = jsonObject.get("checkOutEndTime").getAsString();
            
            // 获取绩点相关字段，如果不存在则使用默认值
            Double maxAttendanceHours = jsonObject.has("maxAttendanceHours") ? 
                jsonObject.get("maxAttendanceHours").getAsDouble() : 8.0;
            Double attendancePercentage = jsonObject.has("attendancePercentage") ? 
                jsonObject.get("attendancePercentage").getAsDouble() : 0.5;
            Double taskPercentage = jsonObject.has("taskPercentage") ? 
                jsonObject.get("taskPercentage").getAsDouble() : 0.5;
            
            // 验证数据
            if (companyId == null || companyId.isEmpty() ||
                checkInStartTime == null || checkInStartTime.isEmpty() ||
                checkInEndTime == null || checkInEndTime.isEmpty() ||
                checkOutStartTime == null || checkOutStartTime.isEmpty() ||
                checkOutEndTime == null || checkOutEndTime.isEmpty()) {
                
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "所有字段都不能为空");
                out.print(gson.toJson(result));
                return;
            }
            
            // 验证百分比之和是否为1.0
            if (Math.abs(attendancePercentage + taskPercentage - 1.0) > 0.001) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "打卡绩点百分比和任务评分百分比之和必须为1.0");
                out.print(gson.toJson(result));
                return;
            }
            
            // 转换时间格式
            SimpleDateFormat format = new SimpleDateFormat("HH:mm");
            
            // 创建打卡设置对象
            AttendanceSetting setting = new AttendanceSetting();
            setting.setCompanyId(companyId);
            
            try {
                setting.setCheckInStartTime(new Time(format.parse(checkInStartTime).getTime()));
                setting.setCheckInEndTime(new Time(format.parse(checkInEndTime).getTime()));
                setting.setCheckOutStartTime(new Time(format.parse(checkOutStartTime).getTime()));
                setting.setCheckOutEndTime(new Time(format.parse(checkOutEndTime).getTime()));
                setting.setMaxAttendanceHours(maxAttendanceHours);
                setting.setAttendancePercentage(attendancePercentage);
                setting.setTaskPercentage(taskPercentage);
            } catch (ParseException e) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "时间格式错误，请使用HH:mm格式");
                out.print(gson.toJson(result));
                return;
            }
            
            // 保存或更新打卡设置
            boolean success = attendanceSettingService.saveOrUpdate(setting);
            
            Map<String, Object> result = new HashMap<>();
            if (success) {
                result.put("success", true);
                result.put("message", "打卡设置保存成功");
            } else {
                result.put("success", false);
                result.put("message", "打卡设置保存失败");
            }
            
            out.print(gson.toJson(result));
            
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "请求数据格式错误: " + e.getMessage());
            out.print(gson.toJson(result));
        }
    }
} 